package com.atguigu.crowd.mvc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

// 表示当前类是一个配置类
@Configuration
// 启用web环境下权限控制功能
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity security) throws Exception {

        // String数组，列出需要放行的资源的路径
        String[] permitUrls = {"/bootstrap/**",
                "/crowd/**", "/css/**", "/fonts/**", "/img/**",
                "/jquery/**", "/layer/**", "/script/**", "/ztree/**", "/admin/to/login/page.html"};

        security
                .authorizeRequests()  // 表示对请求进行授权
                .antMatchers(permitUrls)  // 传入的ant风格的url
                .permitAll()    // 允许上面的所有请求，不需要认证

                .anyRequest()   // 设置其他未设置的全部请求
                .authenticated()   // 表示需要认证

                .and()
                .formLogin()                                        //设置未授权请求跳转到登录页面：开启表单登录功能
                .loginPage("/admin/to/login/page.html")             // 指定登陆页面
                .loginProcessingUrl("/security/do/login.html")      // 设置登录请求的提交地址
                .usernameParameter("loginAcct")                     // 定制登录账号的请求参数名
                .passwordParameter("userPassword")                  // 定制登录密码的请求参数名
                .defaultSuccessUrl("/admin/to/main/page.html")      //设置登录成功后默认前往的 URL 地址

                .and()
                .logout()                                           // 开启退出登录功能
//                .logoutRequestMatcher(new AntPathRequestMatcher("/security/do/logout.html", "GET"))
                .logoutUrl("/security/do/logout.html")               // 设置退出登录的url
                .logoutSuccessUrl("/admin/to/login/page.html")         // 设置退出成功后前往的页面
            ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        // 临时使用内存版登录模式测试代码
//        builder.inMemoryAuthentication().withUser("tom").password("123456").roles("ADMIN");
        // 正式功能中使用基于数据库的认证
        builder.userDetailsService(userDetailsService);


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}
